package com.ny.test2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Bu {
    public static void main(String[] args) {
        // 写入文件
        writeToFile("example.txt");

        // 读取文件
        readFromFile("example.txt");
    }

    public static void writeToFile(String filename) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
            writer.write("这是第一行");
            writer.newLine();
            writer.write("这是第二行");
            writer.newLine();
            writer.write("这是第三行");

            System.out.println("成功写入文件: " + filename);
        } catch (IOException e) {
            System.err.println("写入文件错误: " + e.getMessage());
        }
    }

    public static void readFromFile(String filename) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            System.out.println("\n文件内容:");
            String line;
            int lineNumber = 1;

            while ((line = reader.readLine()) != null) {
                System.out.println(lineNumber + ": " + line);
                lineNumber++;
            }
        } catch (IOException e) {
            System.err.println("读取文件错误: " + e.getMessage());
        }
    }
}